//
//  AreaViewController.m
//  cityCar
//
//  Created by 常宽 on 14/11/5.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "AreaViewController.h"
#import "CityName.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MKGeometry.h>

@interface AreaViewController ()<CLLocationManagerDelegate>

// 区的数组
@property(nonatomic, retain)NSMutableArray *arraySection;
// row的数组
@property(nonatomic, retain)NSMutableArray *arrayRow;
// city名数组
@property(nonatomic, retain)NSMutableArray *cityArr;
// 存区和row的字典
@property(nonatomic, retain)NSMutableDictionary *dictionary;

// 地理反向编码
@property (nonatomic, retain)CLGeocoder *geocoder;

// 定位管理类
@property (nonatomic, retain)CLLocationManager *LocationManager;

@property (nonatomic, retain)UILabel *subTopView;

@end

@implementation AreaViewController

- (void)dealloc
{
    [_cityArr release];
    [_arrayRow release];
    [_arraySection release];
    [_indexBar release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
        self.arraySection = [NSMutableArray array];
        self.arrayRow = [NSMutableArray array];
        self.cityArr = [NSMutableArray array];
        self.dictionary = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[WebColor white]];
    // 加载视图
    [self setupView];
    // 加载数据
    [self startConnection];

}

- (void)setupView
{
    // 屏幕宽和高
    CGFloat x = self.view.frame.size.width;
    CGFloat y = self.view.frame.size.height;
    
    // 顶部View
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, x, 64)];
    [topView setBackgroundColor:[WebColor ghostWhite]];
    [self.view addSubview:topView];
    [topView release];
    
    // 顶部副View(点击定位)
    self.subTopView = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, x, 40)];
    [_subTopView setBackgroundColor:[WebColor lightCyan]];
    _subTopView.text = @"   点击定位";
    _subTopView.userInteractionEnabled = YES;
    [self.view addSubview:_subTopView];
    [_subTopView release];
        
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(positioningAction:)];
    [_subTopView addGestureRecognizer:tap];
    [tap release];
    
    // 顶部View上返回button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(5, 20, 44, 44)];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:20.f];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(returnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    // 初始化第三方属性indexBar 签订协议
    self.indexBar = [[BATableView alloc] initWithFrame:CGRectMake(0, 64 + 50, x, y - 64)];
    self.indexBar.delegate = self;
    [self.view addSubview:self.indexBar];
    [_indexBar release];

}

// 点击定位
- (void)positioningAction:(UITapGestureRecognizer *)sender
{
    NSLog(@"定位");
    // 判断设备是否可以定位
    if ([CLLocationManager locationServicesEnabled]) {
        self.LocationManager = [[CLLocationManager alloc]init];
        self.LocationManager.delegate = self;
        
        //选择定位的方式为最优的状态.
        self.LocationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        //出发事件的最小距离
        self.LocationManager.distanceFilter = 0.1f;
        
        [self.LocationManager requestAlwaysAuthorization];

        [self.LocationManager startUpdatingLocation];
    }
}

#pragma mark 定位协议
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    
    NSLog(@"%f",currentLocation.coordinate.latitude);
    NSLog(@"%f",currentLocation.coordinate.longitude);
    
    
    self.geocoder = [[CLGeocoder alloc]init];
    [self.geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        CLPlacemark *p = [placemarks lastObject];
        NSString *str = p.country; //国
        NSString *str1 = p.locality;// 市
        NSString *str2 = p.administrativeArea;// 省(行政地区)
        if ([str isEqualToString:@"中国"] || [str isEqualToString:@"China"]) {
            NSLog(@"国家:%@ , 城市:%@",str, str1);
            
            // 字符串处理
            str2 = [str2 substringToIndex:([str2 length] - 1)];
            str1 = [str1 substringToIndex:([str1 length] - 1)];
            self.subTopView.text = [NSString stringWithFormat:@"   %@省,%@市", str2, str1];
            
//#warning 准备传值
            for (NSString *key in self.arraySection) {
                for (CityName *city in [self.dictionary objectForKey:key]) {
                    if ([str1 isEqualToString:city.city] && [str2 isEqualToString:city.pro]) {
//#warning 消息中心
                        // 发消息
                        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
                        [center postNotificationName:@"CityName" object:city userInfo:nil];
                        
                        // 获得的地名存本地
                        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                        NSString *documentPath = [paths lastObject];
                        NSString *arrPath = [documentPath stringByAppendingPathComponent:@"area.xml"];
                        
                        NSArray *readArr = [NSArray arrayWithObjects:city.pro, city.city, nil];
                        BOOL result2 = [readArr writeToFile:arrPath atomically:YES];
                        NSLog(@"数组写入结果: %d", result2);

                        
                        [self.navigationController setNavigationBarHidden:NO animated:YES];
                        [self.tabBarController.tabBar setHidden:NO];
                        
                        [self.navigationController popViewControllerAnimated:YES];
                        
                        [self dismissViewControllerAnimated:YES completion:^{
                        }];
                        break;
                    }
                }
            }
            
            
        } else {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"⚠️警告\n warning" message:@"此功能仅中国地区可用\n This feature is only available in China" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];
            [alertView release];
        }
    }];
    [_geocoder release];
    [self.LocationManager stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"失败了");
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"警告\n warning" message:@"定位失败\n Positioning failure" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}
#pragma mark -

// 网络获取列表
- (void)startConnection
{
    NSString *str  = @"http://mrobot.pcauto.com.cn/v2/cms/area_tree";
    [Connection networkHandlerWith:str block:^(id result) {
        NSArray *arr = [result valueForKey:@"area"];
        for (NSArray *arr1 in arr) {
            CityName *city = [[CityName alloc] init];
            city.pro = [arr1 objectAtIndex:3];
            city.city = [arr1 objectAtIndex:1];
            // 把汉字拼音首字母取出
            NSMutableString *ms = [[NSMutableString alloc] initWithString:city.city];
            if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
                NSString *mStr = [ms substringToIndex:1];
                if (![self.arraySection containsObject:mStr]) {
                    [self.arraySection addObject:mStr];
                }
                city.index = mStr;
                
            }
            
            [self.cityArr addObject:city];
            [city release];
        }
        
        
        for (int i = 0; i < self.arraySection.count; i++) {
            for (int j = 0; j < self.arraySection.count - i - 1; j++) {
                if ([self.arraySection[j] compare:self.arraySection[j + 1]] > 0) {
                    NSString *t = @"0";
                    t = self.arraySection[j + 1];
                    self.arraySection[j + 1] = self.arraySection[j];
                    self.arraySection[j] = t;
                }
            }
        }
        for (int i = 0; i < self.arraySection.count; i++) {
            self.arrayRow = [NSMutableArray array];
            for (CityName *city in self.cityArr) {
                if ([self.arraySection[i] isEqualToString:city.index]) {
                    [self.arrayRow addObject:city];
                }
            }
            [self.dictionary setValue:self.arrayRow forKey:self.arraySection[i]];
        }
        
        //NSLog(@"%@", self.dictionary);
        [self.indexBar reloadData];
    }];
}

#pragma mark BATableView
- (NSArray *)sectionIndexTitlesForABELTableView:(BATableView *)tableView
{
    // 返回给第三方一个索引数组
    return self.arraySection;
}


#pragma mark tableView 协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.arraySection.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.arraySection[section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr = [self.dictionary objectForKey:[self.arraySection objectAtIndex:section]];
    return arr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse1Area"];
    if (!cell) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse1Area"]autorelease];
    }
    
    CityName *city = [[self.dictionary objectForKey:[self.arraySection objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    cell.textLabel.text = city.city;
    return cell;
    
}

//#warning cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CityName *city = [[self.dictionary objectForKey:[self.arraySection objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    NSLog(@"%@, %@", city.city, city.pro);
    
    // 获得的地名存本地
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [paths lastObject];
    NSString *arrPath = [documentPath stringByAppendingPathComponent:@"area.xml"];
    
    NSArray *readArr = [NSArray arrayWithObjects:city.pro, city.city, nil];
    BOOL result2 = [readArr writeToFile:arrPath atomically:YES];
    NSLog(@"数组写入结果: %d", result2);

    // 发消息
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"CityName" object:city userInfo:nil];
//    self.block(city);
    
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.tabBarController.tabBar setHidden:NO];
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
    
}


// 返回
- (void)returnAction:(UIButton *)button
{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController popViewControllerAnimated:YES];
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
